﻿using CRMG.Container.Source.Variables;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace CRMG.Container.UserControl
{
    public class GuruComboBox : ComboBox
    {
        protected List<Op> OpList;
        protected object _value = null;
        public GuruComboBox()
            : base()
        {
            InitComp();
            OpList = new List<Op>();
            _value = null;
        }

        protected void InitComp()
        {
            this.SuspendLayout();
            this.Anchor = System.Windows.Forms.AnchorStyles.None;
            this.DropDownStyle = ComboBoxStyle.DropDownList;
            this.Font = new System.Drawing.Font("Segoe UI", 10.0f, System.Drawing.FontStyle.Regular);
            this.Text = string.Empty;
            this.ResumeLayout(false);
            this.PerformLayout();
        }


        protected override void OnSelectedIndexChanged(EventArgs e)
        {
            base.OnSelectedIndexChanged(e);
            SetSelectionValue();
        }

        protected void SetSelectionValue()
        {
            try
            {
                _value = OpList[this.SelectedIndex].Value;
            }
            catch (Exception)
            {
                _value = null;
            }
        }

        public object SelectionValue
        {
            get { return _value; }
        }


        public void SetItemSource(string itemList, char itemDelimiter, char propDelimiter)
        {
            if (string.IsNullOrWhiteSpace(itemList) || Char.ToString(itemDelimiter).Equals(string.Empty) || Char.ToString(propDelimiter).Equals(string.Empty))
            {
                return;
            }
            else
            {
                try
                {
                    string[] itemsSrc = itemList.Split(itemDelimiter);
                    string[] strarr;
                    Op _op;
                    foreach (string item in itemsSrc)
                    {
                        strarr = item.Split(propDelimiter);
                        if (strarr != null)
                        {
                            if (strarr.Length == 2)
                            {
                                _op = new Op { Text = strarr[0], Value = strarr[1] };
                                OpList.Add(_op);
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    OpList = new List<Op>();
                }
                this.DataSource = OpList;
                this.SelectedIndex = -1;
            }
        }

    }
}
